import router from "@/routers/router";
import NProgress from "@/config/nprogress";
import {GlobalStore} from "@/store";
import {AxiosCanceler} from "@/api/helper/axiosCancel";
import {handleRouter} from "@/utils/util";
import {RouteRecordRaw} from "vue-router";

const axiosCanceler = new AxiosCanceler();

// * 路由拦截 beforeEach
router.beforeEach((to, from, next) => {
	NProgress.start();
	// * 在跳转路由之前，清除所有的请求
	axiosCanceler.removeAllPending();

	// 判断目标路由是否存在，没有就加载动态路由
	const allPath = router.getRoutes().map(v => v['path']);
	if (allPath.indexOf(to.path) === -1) {
		const dynamicRouter = localStorage.getItem('MenuState')
		if (dynamicRouter) {
			const dynamicRouterObj = JSON.parse(dynamicRouter)
			if (dynamicRouterObj.menuList) {
				const routerList = handleRouter(dynamicRouterObj.menuList);
				routerList.forEach((item: RouteRecordRaw) => {
					router.addRoute(item);
				})

				// * 判断当前路由是否需要访问权限
				if (!to.matched.some(record => record.meta.requiresAuth)) return next();
				// * 判断是否有Token
				const globalStore = GlobalStore();
				if (!globalStore.token) {
					next({
						path: "/login"
					});
					NProgress.done();
					return;
				}

				return next();
			} else {
				return next({
					path: "/404"
				});
			}
		} else {
			return next({
				path: "/404"
			});
		}
	} else {
		// * 判断当前路由是否需要访问权限
		if (!to.matched.some(record => record.meta.requiresAuth)) return next();
		// * 判断是否有Token
		const globalStore = GlobalStore();
		if (!globalStore.token) {
			next({
				path: "/login"
			});
			NProgress.done();
			return;
		}

		return next();
	}
});

router.afterEach(() => {
	NProgress.done();
});

export default router;
